//
//  PublicMethodEngine.m
//  GrowUP
//
//  Created by Hobo.Chen on 7/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PublicMethodEngine.h"


@implementation PublicMethodEngine
static PublicMethodEngine *_shareEngine = nil;

+ (PublicMethodEngine *)sharedPublicMethodEngine
{
	if (!_shareEngine) {
		_shareEngine = [[PublicMethodEngine alloc] init];
	}
	
	return _shareEngine;
}

- (NSString *)dataFilePath:(NSString *)filename
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:filename];
}

- (BOOL)saveData:(NSData *)data filePath:(NSString *)filePath
{
	if ([[NSFileManager defaultManager] isExecutableFileAtPath:filePath]) {
		[self deleteFileWith:filePath];
	}
    
    if (![self isFolderExitWith:filePath]) {
        
      	BOOL isSave = [data writeToFile:filePath atomically:NO];
	
	[data release];
	
	return isSave;

        
    }
    
     	
}

//read data from file

- (NSData *)readData:(NSString *)filePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSData *data=[fileManager contentsAtPath:filePath];
    return data;
}


- (NSString *)pathOfFileWithSuffix:(NSString *)suffix folder:(NSString *)folder
{
	return [self filename:[self dateInFormat:@"%s"] 
				   suffix:suffix folder:folder];
}

- (NSString *)filename:(NSString *)filename  suffix:(NSString *)suffix folder:(NSString *)folder
{
	NSString *newFilename = [NSString stringWithString:filename];
	NSMutableString *file = [NSMutableString stringWithFormat:@"%@/%@.%@",folder, newFilename,suffix];
	
	NSString *path = [self dataFilePath:file];
	
	while ([[NSFileManager defaultManager] isExecutableFileAtPath:path]) {
		NSString *newFilename2 = [NSString stringWithFormat:@"%@0",newFilename];
		newFilename = [NSString stringWithString:newFilename2];
		
		NSMutableString *file = [NSMutableString stringWithFormat:@"%@/%@.%@", folder, newFilename,suffix];
		
		path = [self dataFilePath:file];
	}
	
	return path;
}

//获取为unix时间:NSString *unixTime = [self dateInFormat:@"%s"];
- (NSString *)dateInFormat:(NSString*) stringFormat 
{
	char buffer[80];
	const char *format = [stringFormat UTF8String];
	time_t rawtime;
	struct tm * timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(buffer, 80, format, timeinfo);
	return [NSString  stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

-(BOOL)deleteFileWith:(NSString *)path
{
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    BOOL fileExists = [fileManager fileExistsAtPath:path];

    if (fileExists) 
    {
        BOOL success = [fileManager removeItemAtPath:path error:&error];
        if (!success){
			
			return NO;
		}
		else {
			return YES;
		}
		
    }
	
	return YES;
}

- (BOOL)isFolderExitWith:(NSString *)filePath
{
	NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL fileExists = [fileManager fileExistsAtPath:filePath];
	
	return fileExists;
	
}

- (NSString *)documentPathWithFolder:(NSString *)folder{
	NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:folder];
	return path;
}

- (BOOL)createFolder:(NSString *)folder
{
	NSString *path = [self documentPathWithFolder:folder];
	NSError *error;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:0 error:&error]){
        NSLog(@"Error creating path %@ [%@]", path, error);
		return NO;
	}
	else {
		NSLog(@"create folder successfully :%@",path);
	}
	
	return YES;
}


#pragma mark -
#pragma mark  get data from dict
- (int)getIntFromDict:(NSDictionary *)dict keyStr:(NSString *)ketStr
{
	if ([dict objectForKey:ketStr]) {
		return [[dict objectForKey:ketStr] intValue];
	}
	else {
		return 0;
	}
}

- (NSString *)getStrFromDict:(NSDictionary *)dict keyStr:(NSString *)ketStr
{
	if (dict) {
		if ([dict objectForKey:ketStr]) {
			NSString *string = (NSString *)[dict objectForKey:ketStr];
			return [string copy];
		}
		else {
			return nil;
		}
	}
	else {
		return nil;
	}

}


- (BOOL)getBoolFromDict:(NSDictionary *)dict keyStr:(NSString *)keyStr
{
	if ([dict objectForKey:keyStr]) {
		return [[dict objectForKey:keyStr] boolValue];
	}
	else {
		return NO;
	}
	
}

- (NSData *)getDataFromDict:(NSDictionary *)dict keyStr:(NSString *)keyStr
{
	if ([dict objectForKey:keyStr]) {
		NSData *data = [[dict objectForKey:keyStr] data];
		return [data copy];
	}
	else {
		return nil;
	}
	
}

- (NSDate *)getDateFromDict:(NSDictionary *)dict keyStr:(NSString *)keyStr
{
	if ([dict objectForKey:keyStr]) {
		NSString *string = (NSString *)[dict objectForKey:keyStr];
		return [self NSStringDateToNSDate:string];
	}
	else {
		return nil;
	}
	
}



#pragma mark - NSDate 处理

-(NSString *)NSDateToNSTring:(NSDate *)nsDate
{
	
	//NSString *string = [nsDate descriptionWithCalendarFormat:@"%Y/%m/%d %H:%M:%S" timeZone:nil locale:nil];此方法为是有API如果要上传APP不要使用
	
	NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
	[fmt setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
	[fmt setDateFormat:kDEFAULT_DATE_TIME_FORMAT];
	
	NSString *string=[fmt stringFromDate:nsDate];
	
	return string;
	
} 

- (NSDate *)NSStringDateToNSDate:(NSString *)string 
{    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
    [formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT];
    NSDate *date = [formatter dateFromString:string];
    [formatter release];
    return date;
    
}

- (NSDate *) dateWithDaysFromDate: (NSUInteger) days date:(NSDate *)date
{
	NSTimeInterval aTimeInterval = [date
									timeIntervalSinceReferenceDate] + D_DAY * days;
	NSDate *newDate = [NSDate
					   dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;	
}

#pragma mark -

-(UIImage *)imageFromText:(NSString *)text width:(float)width height:(float)height
{
    // set the font type and size
    UIFont *font = [UIFont systemFontOfSize:12.0];  
    CGSize size  = CGSizeMake(width, height);// [text sizeWithFont:font];
	
    // check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
    if (UIGraphicsBeginImageContextWithOptions != NULL)
        UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
    else
        // iOS is < 4.0 
        UIGraphicsBeginImageContext(size);
	
    // optional: add a shadow, to avoid clipping the shadow you should make the context size bigger 
    //
//	CGContextRef ctx = UIGraphicsGetCurrentContext();
//	CGContextSetShadowWithColor(ctx, CGSizeMake(1.0, 1.0), 5.0, [[UIColor grayColor] CGColor]);
	
	UIImage *bgImage = [UIImage imageNamed:@"p2_bg_2.png"];
	[bgImage drawInRect:CGRectMake(0, 0, width, height)];
	
    // draw in context, you can use also drawInRect:withFont:
    //[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
	[text drawInRect:CGRectMake(5, 5, width, height) withFont:font];
	
    // transfer image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	[image retain];
    UIGraphicsEndImageContext();    
	
    return image;
}

-(UIImage *)compresImageWith:(UIImage *)image maxPix:(float)maxPix
{
    
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
	
    float widthScale = imageWidth /maxPix;
    float heightScale = imageHeight /maxPix;
	
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    
    CGSize size;
    if (widthScale <=1 && heightScale <=1 ) {
        size = CGSizeMake(imageWidth, imageHeight);
    }
    else if(widthScale >= heightScale){
        size = CGSizeMake(imageWidth /widthScale, imageHeight /widthScale);
    }
    else {
        size = CGSizeMake(imageWidth /heightScale, imageHeight /heightScale);
    }
    
    UIGraphicsBeginImageContext(size);
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
	
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [newImage retain];
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
	
    return newImage;
    
}

-(NSData *)compresImageDataWith:(UIImage *)image maxPix:(float)maxPix
{
    
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
	
    float widthScale = imageWidth /maxPix;
    float heightScale = imageHeight /maxPix;
	
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    
    CGSize size;
    if (widthScale <=1 && heightScale <=1 ) {
        size = CGSizeMake(imageWidth, imageHeight);
    }
    else if(widthScale >= heightScale){
        size = CGSizeMake(imageWidth /widthScale, imageHeight /widthScale);
    }
    else {
        size = CGSizeMake(imageWidth /heightScale, imageHeight /heightScale);
    }
    
    UIGraphicsBeginImageContext(size);
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
	
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [newImage retain];
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
	
    
    NSData *data = UIImageJPEGRepresentation(newImage, PHOTO_QUALITY);
    [newImage release];
    return data;
}

-(UIImage *)compresImageWith:(UIImage *)image width:(float)width height:(float)height
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
	
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
	
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
	
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake((width -imageWidth /heightScale) /2, 0, imageWidth /heightScale , height)];   
    }
    else {
        [image drawInRect:CGRectMake(0, (height -imageHeight /widthScale) /2, width , imageHeight /widthScale)];
    }
	
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [newImage retain];
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
	
    return newImage;
	
}

//将一张图片向左或向右旋转90度
- (UIImage *)rotImageRightOrLeft:(UIImage *)image isRight:(BOOL)isRight
{
    float imageWidth =  image.size.width;
    float imageHeight = image.size.height;
    
    NSLog(@"width %f, height %f", imageWidth, imageHeight);
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context，由于是固定左右90度所以大小横竖颠倒
    UIGraphicsBeginImageContext(CGSizeMake(imageHeight, imageWidth));
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    float rotRadians;

    //旋转后会使context转出去，所以要给个平移
    if (isRight) {
        rotRadians = degreesToRadian(90.0);
        NSLog(@"Radians %f", rotRadians);
        CGContextTranslateCTM(context,imageHeight,0);
    }
    else {
        rotRadians = degreesToRadian(-90.0);
        NSLog(@"Radians %f", rotRadians);
        CGContextTranslateCTM(context,0, imageWidth);
    }
    
    //旋转
    CGContextRotateCTM( context,rotRadians);
    
    //最后把图片绘制出来
    [image drawInRect:CGRectMake(0, 0, imageWidth, imageHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [newImage retain];
    
    //使当前的context出堆栈
    UIGraphicsEndImageContext();
	
    return newImage;
}


//将一张图片向左或向右旋转angle度
- (UIImage *)rotImageZeroWith:(UIImage *)image rotAngle:(float)angle
{
    float imageWidth =  image.size.width;
    float imageHeight = image.size.height;
    
    NSLog(@"width %f, height %f", imageWidth, imageHeight);
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context，由于是固定左右90度所以大小横竖颠倒
    UIGraphicsBeginImageContext(CGSizeMake(imageWidth, imageHeight));

    //最后把图片绘制出来
    [image drawInRect:CGRectMake(0, 0, imageWidth, imageHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [newImage retain];
    
    //使当前的context出堆栈
    UIGraphicsEndImageContext();
	
    return newImage;
}


#pragma mark --
#pragma mark String to dictionary
- (NSMutableDictionary *)stringToDictionary:(NSString *)string{
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    NSMutableString *key = [[NSMutableString alloc]init];
    NSMutableString *value = [[NSMutableString alloc]init];
    
    
    for (int i = 0; i<string.length;i++) {
        
        NSString *s=[string substringWithRange:NSMakeRange(i ,1)];
        if (![s isEqualToString:@":"]) {
            [key appendString:s];
        }
        else{
            
            int j=i+1;
            
            for (j = i+1; j<string.length; j++) {
                
                NSString *str=[string substringWithRange:NSMakeRange(j ,1)];
                if (![str isEqualToString:@";"]) {
                    [value appendString:str];
                }
                else{
                    
                    CLog(@"key : %@  \nvalue:%@", key,value);
                    
                    NSString *_value = [NSString stringWithFormat:@"%@",value];
                    
                    
                    
                    CLog(@"_value %@", _value);
                    
                    [dict setObject:_value forKey:key];
                    
                    int keylength=key.length;
                    [key deleteCharactersInRange:NSMakeRange(0,keylength )];
                    [value deleteCharactersInRange:NSMakeRange(0, value.length)];
                    break;
                    
                }
                
            }
            i = j;
            
        }
        
        
    }
    
    CLog(@"String to dict %@ ", dict);
    
    return dict;
    
}




//in = in.replaceAll("&", "&amp;");
//in = in.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
//in = in.replaceAll("\r", "");
//in = in.replaceAll("\n", "<br>");
//in = in.replaceAll("\"", "&quot;");
//in = in.replaceAll(" ", "&nbsp;");
//in = in.replaceAll("'", "&acute;");


-(NSString *)changeStringFommat:(NSString *)str{
    
    if ([str isMemberOfClass:[NSNull class]]) {
        return @"";
    }
    
    NSString *string;
    if (![str isMemberOfClass:[NSNull class]]) {
        
        string = [str stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"]; 
    }
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
             
    }
    
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&acute;" withString:@"'"];
    }
    
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    }
    
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&acute;" withString:@"'"];
    }
    
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    }
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    }
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    }
    
    return string;
    
}



#pragma mark - 空间检测
- (float)getFreeDiskspaceMiB {
    NSError *error = nil;  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];  
    
//    if (dictionary) {  
//        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];  
//        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
//        totalSpace = [fileSystemSizeInBytes floatValue];
//        totalFreeSpace = [freeFileSystemSizeInBytes floatValue];
//        CLog(@"Memory Capacity of %f MiB with %f MiB Free memory available.", ((totalSpace/1024.0f)/1024.0f), ((totalFreeSpace/1024.0f)/1024.0f));
//        CLog(@"Memory Capacity of %f G with %f G Free memory available.", (((totalSpace/1024.0f)/1024.0f)/1024.0f), (((totalFreeSpace/1024.0f)/1024.0f)/1024.0f));
//    } else {  
//        CLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);  
//    }  
    
    if (dictionary) {  
        double totalSpace = [[dictionary objectForKey: NSFileSystemSize] longLongValue];  
        double totalFreeSpace = [[dictionary objectForKey:NSFileSystemFreeSize] longLongValue];

        CLog(@"Memory Capacity of %f MiB with %f MiB Free memory available.", ((totalSpace/1024.0f)/1024.0f), ((totalFreeSpace/1024.0f)/1024.0f));
        CLog(@"Memory Capacity of %f G with %f G Free memory available.", (((totalSpace/1024.0f)/1024.0f)/1024.0f), (((totalFreeSpace/1024.0f)/1024.0f)/1024.0f));
        
        float freeDiskMib = (totalFreeSpace/1024.0f)/1024.0f;
        
        return freeDiskMib;
        
    } else {  
        CLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);
        
        return -MAXFLOAT;
    }

}

@end
